/**
 * meituan.com Inc.
 * Copyright (c) 2010-2023 All Rights Reserved.
 */
package com.recruit.controller;

/**
 * <p>
 *
 * </p>
 *
 * @author denghufu
 * @version MsgInfoController.java v1.0 2023/3/7 19:26 denghufu Exp $
 */

import com.recruit.dto.chat.MsgInfoDTO;
import com.recruit.mapper.MsgInfoMapper;
import com.recruit.mapper.SessionListMapper;
import com.recruit.model.MsgInfoDO;
import com.recruit.model.SessionListDO;
import com.recruit.service.MsgInfoService;
import com.recruit.vo.PageResponseVO;
import com.recruit.vo.UnifyResponseVO;
import io.github.talelin.core.annotation.Logger;
import io.github.talelin.core.annotation.PermissionModule;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/recruit/msg")
@PermissionModule(value = "聊天信息")
@Api(tags = "聊天信息")
@Slf4j
@Validated
public class MsgInfoController {

    @Resource
    private MsgInfoMapper msgInfoMapper;

    @Resource
    private SessionListMapper sessionListMapper;

    @Resource
    private MsgInfoService msgInfoService;

    /**
     * 消息列表
     *
     * @param sessionId
     * @return
     */
    @GetMapping("/msgList")
    public UnifyResponseVO msgList(@RequestParam Integer sessionId) {
        SessionListDO sessionList = sessionListMapper.selectByPrimaryKey(sessionId);
        if (sessionList == null) {
            return new UnifyResponseVO();
        }
        Integer fromUserId = sessionList.getUserId();
        Integer toUserId = sessionList.getToUserId();
        List<MsgInfoDO> msgInfoList = msgInfoMapper.selectMsgList(fromUserId, toUserId);
        // 更新消息已读
        msgInfoMapper.msgRead(fromUserId, toUserId);
        // 更新会话里面的未读消息
        sessionListMapper.delUnReadCount(fromUserId, toUserId);
        return new UnifyResponseVO(msgInfoList);
    }

    @ApiOperation("获取聊天信息")
    @GetMapping("/listMsg")
    public PageResponseVO<MsgInfoDTO> listMsgList(Integer fromId, Integer toId){
        if (Objects.isNull(fromId) || Objects.isNull(toId)){
            throw new RuntimeException("请选择聊天对象");
        }
        List<MsgInfoDTO> msgInfoDOS = msgInfoService.listMsgInfoById(fromId, toId);
        PageResponseVO<MsgInfoDTO> result = new PageResponseVO<MsgInfoDTO>();
        result.setItems(msgInfoDOS);
        return result;
    }

    @ApiOperation("添加聊天信息")
    @PostMapping("/gradualist")
    public UnifyResponseVO addMsgList(@RequestBody MsgInfoDO msgInfoDO){
        log.info(String.valueOf(msgInfoDO));
        if (msgInfoDO==null){
            return new UnifyResponseVO("对象为空");
        }
        msgInfoService.insertMsg(msgInfoDO);
        return new UnifyResponseVO();
    }

}

